﻿using System;
using System.Text;
using System.Drawing;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public static partial class NativeAOT
{
    [UnmanagedCallersOnly(EntryPoint = "ffts")]
    public static unsafe double ffts(double a, double b, double eps, IntPtr f_x_ptr)
    {
        f_x = Marshal.GetDelegateForFunctionPointer<delegatefunc_x>(f_x_ptr);

        return ffts(a, b, eps);
    }

    /// <summary>
    /// 梯形求积法
    /// f计算被积函数值f(x)的函数名。
    /// </summary>
    /// <param name="a">积分下限。</param>
    /// <param name="b">积分上限。要求b>a。</param>
    /// <param name="eps">积分精度要求。</param>
    /// <returns>函数返回积分值。</returns>
    public static unsafe double ffts(double a, double b, double eps = 1.0E-6)
    {
        int n, k;
        double fa, fb, h, t1, p, s, x, t = 0.0;

        fa = f_x(a);
        fb = f_x(b);
        n = 1; h = b - a;
        t1 = h * (fa + fb) / 2.0;
        p = eps + 1.0;
        while (p >= eps)
        {
            s = 0.0;
            for (k = 0; k <= n - 1; k++)
            {
                x = a + (k + 0.5) * h;
                s = s + f_x(x);
            }
            t = (t1 + h * s) / 2.0;
            p = Math.Abs(t1 - t);
            t1 = t; n = n + n; h = h / 2.0;
        }
        return (t);
    }

    /*
    // 梯形求积法例
      int main()
      { 
          double a,b,eps,t,fftsf(double);
          a=0.0; b=1.0; eps=0.000001;
          t=ffts(a,b,eps,fftsf);
          cout <<"t = " <<t <<endl;
          return 0;
      }
    // 计算被积函数值
      double fftsf(double x)
      { 
          return(exp(-x*x));
      }
    */
}

